<?php

namespace app\api\controller;

use think\facade\View;
use think\facade\Lang;
use think\facade\Db;

/**
 * ============================================================================
 * DSKMS多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 卖家代金券控制器
 */
class Sellervoucher extends MobileSeller {

    private $quotastate_arr;

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/sellervoucher.lang.php');
        if (config('ds_config.voucher_allow') != 1) {
            ds_json_encode(10001, lang('voucher_unavailable'));
        }
        //套餐状态
        $this->quotastate_arr = array(
            'activity' => array(1, lang('voucher_quotastate_activity')),
            'cancel' => array(2, lang('voucher_quotastate_cancel')),
            'expire' => array(3, lang('voucher_quotastate_expire'))
        );
    }

    /**
     * @api {POST} api/Sellervoucher/templatelist 代金券列表
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} txt_keyword 关键词
     * @apiParam {String} select_state 状态 1:有效 2:失效
     * @apiParam {String} txt_startdate 有效期开始时间 YYYY-MM-DD
     * @apiParam {String} txt_enddate 有效期结束时间 YYYY-MM-DD
     * @apiParam {String} page 页码
     * @apiParam {String} pagesize 每页显示数量
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.current_quota  代金券活动信息 （返回字段参考voucherquota）
     * @apiSuccess {String} result.promotion_voucher_price  购买代金劵活动所需费用
     * @apiSuccess {String} result.voucher_storetimes_limit  每月最多可以发布的代金劵促销活动数量
     * @apiSuccess {Object} result.vouchertemplate_list  代金券模板列表 （返回字段参考vouchertemplate）
     * @apiSuccess {Int} result.page_total  总页数
     * @apiSuccess {Boolean} result.hasmore  是否有更多 true是false否
     */
    public function templatelist() {
        //检查过期的代金券模板状态设为失效
        $this->check_voucher_template_expire();
        $voucher_model = model('voucher');
            //查询是否存在可用套餐
            $current_quota = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
        //查询列表
        $condition = array();
        $condition[] = array('vouchertemplate_store_id','=',$this->store_info['store_id']);
        if (trim(input('param.txt_keyword'))) {
            $condition[] = array('vouchertemplate_title','like', '%' . trim(input('param.txt_keyword')) . '%');
        }
        $select_state = intval(input('param.select_state'));
        if ($select_state) {
            $condition[] = array('vouchertemplate_state','=',$select_state);
        }
        if (input('param.txt_startdate')) {
            $condition[] = array('vouchertemplate_enddate','>=', strtotime(input('param.txt_startdate')));
        }
        if (input('param.txt_enddate')) {
            $condition[] = array('vouchertemplate_startdate','<=', strtotime(input('param.txt_enddate')));
        }

        $vouchertemplate_list_ = Db::name('vouchertemplate')->where($condition)->order('vouchertemplate_id desc')->paginate(10, false, ['query' => request()->param()]);

        $vouchertemplate_list = $vouchertemplate_list_->items();
        foreach ($vouchertemplate_list as $key => $val) {

            if (!$val['vouchertemplate_customimg']) {
                $vouchertemplate_list[$key]['vouchertemplate_customimg'] = ds_get_pic(ATTACH_COMMON,config('ds_config.default_goods_image'));
            } else {
                $vouchertemplate_list[$key]['vouchertemplate_customimg'] = ds_get_pic( ATTACH_VOUCHER . DIRECTORY_SEPARATOR . $this->store_info['store_id'] , $val['vouchertemplate_customimg']);
            }
        }


        $result = array_merge(array('vouchertemplate_list' => $vouchertemplate_list, 'current_quota' => $current_quota, 'promotion_voucher_price' => config('ds_config.promotion_voucher_price'), 'voucher_storetimes_limit' => config('ds_config.voucher_storetimes_limit')), mobile_page($vouchertemplate_list_));
        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellervoucher/quotaadd 购买套餐
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} quota_quantity 购买数量
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.voucherquota_endtime  代金券活动结束时间
     */
    public function quotaadd() {
        if (intval(config('ds_config.promotion_voucher_price')) == 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        $quota_quantity = intval(input('post.quota_quantity'));
        if ($quota_quantity <= 0 || $quota_quantity > 12) {
            ds_json_encode(10001, lang('voucher_apply_num_error'));
        }
        //获取当前价格
        $current_price = intval(config('ds_config.promotion_voucher_price'));
        
        //记录机构费用
        $this->recordStorecost($current_price * $quota_quantity, lang('buy_voucher_package'));
        
        $voucher_model = model('voucher');

        //获取该用户已有套餐
        $current_quota = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
        $quota_add_time = 86400 * 30 * $quota_quantity;
        if (empty($current_quota)) {
            //生成套餐
            $param = array();
            $param['voucherquota_memberid'] = $this->seller_info['member_id'];
            $param['voucherquota_membername'] = $this->seller_info['seller_name'];
            $param['voucherquota_storeid'] = $this->store_info['store_id'];
            $param['voucherquota_storename'] = $this->store_info['store_name'];
            $param['voucherquota_starttime'] = TIMESTAMP;
            $param['voucherquota_endtime'] = TIMESTAMP + $quota_add_time;
            $param['voucherquota_state'] = 1;
            $reault = Db::name('voucherquota')->insert($param);
        } else {
            $param = array();
            $param['voucherquota_endtime'] = $current_quota['voucherquota_endtime'] + $quota_add_time;
            $reault = Db::name('voucherquota')->where(array('voucherquota_id' => $current_quota['voucherquota_id']))->update($param);
        }



        $this->recordSellerlog(lang('buy') . $quota_quantity . lang('voucher_plan') . $current_price . lang('ds_yuan'));

        if ($reault) {
            ds_json_encode(10000, lang('voucher_apply_buy_succ'), array('voucherquota_endtime' => $param['voucherquota_endtime']));
        } else {
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }
    }

    /**
     * @api {POST} api/Sellervoucher/templateadd 代金券模版添加
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} txt_template_title 代金券模版名称
     * @apiParam {String} txt_template_total 代金券总数
     * @apiParam {String} select_template_price 面额
     * @apiParam {String} txt_template_limit 订单限额
     * @apiParam {String} txt_template_describe 代金券模版描述
     * @apiParam {String} txt_template_enddate 有效期结束时间 YYYY-MM-DD
     * @apiParam {String} storeclass_id 所属机构分类ID
     * @apiParam {String} eachlimit 每人限领张数
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function templateadd() {
        $voucher_model = model('voucher');
        $quotainfo = array();
            //查询当前可以使用的套餐
            $quotainfo = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
            if (empty($quotainfo)) {
                if (intval(config('ds_config.promotion_voucher_price')) == 0) {
                    $quotainfo = array('voucherquota_id' => 0, 'voucherquota_starttime' => TIMESTAMP, 'voucherquota_endtime' => TIMESTAMP + 86400 * 30); //没有套餐时，最多一个月
                } else {
                    ds_json_encode(10001, lang('voucher_template_quotanull'));
                }
            }

            //查询该套餐下代金券模板列表
            $count = Db::name('vouchertemplate')->where(array('vouchertemplate_quotaid' => $quotainfo['voucherquota_id'], 'vouchertemplate_state' => 1))->count();
            if ($count >= config('ds_config.voucher_storetimes_limit')) {
                $message = sprintf(lang('voucher_template_noresidual'), config('ds_config.voucher_storetimes_limit'));
                ds_json_encode(10001, $message);
            }
        $pricelist = Db::name('voucherprice')->order('voucherprice asc')->select()->toArray();
        //验证提交的内容面额不能大于限额
        $data = [
            'txt_template_title' => input('post.txt_template_title'),
            'txt_template_total' => input('post.txt_template_total'),
            'select_template_price' => input('post.select_template_price'),
            'txt_template_limit' => input('post.txt_template_limit'),
            'txt_template_describe' => input('post.txt_template_describe'),
        ];

        $sellervoucher_validate = ds_validate('sellervoucher');
        if (!$sellervoucher_validate->scene('templateadd')->check($data)) {
            ds_json_encode(10001, $sellervoucher_validate->getError());
        }
        //金额验证
        $price = intval(input('post.select_template_price')) > 0 ? intval(input('post.select_template_price')) : 0;
        foreach ($pricelist as $k => $v) {
            if ($v['voucherprice'] == $price) {
                $chooseprice = $v; //取得当前选择的面额记录
            }
        }
        if (empty($chooseprice)) {
            ds_json_encode(10001, lang('voucher_template_pricelisterror'));
        }
        $limit = intval(input('post.txt_template_limit')) > 0 ? intval(input('post.txt_template_limit')) : 0;
        if ($price >= $limit) {
            ds_json_encode(10001, lang('voucher_template_price_error'));
        }
        $insert_arr = array();
        $insert_arr['vouchertemplate_title'] = trim(input('post.txt_template_title'));
        $insert_arr['vouchertemplate_desc'] = trim(input('post.txt_template_describe'));
        $insert_arr['vouchertemplate_startdate'] = TIMESTAMP; //默认代金券模板的有效期为当前时间
        if (input('post.txt_template_enddate')) {
            $enddate = strtotime(input('post.txt_template_enddate'));
            if ($enddate > $quotainfo['voucherquota_endtime']) {
                $enddate = $quotainfo['voucherquota_endtime'];
            }
            $insert_arr['vouchertemplate_enddate'] = $enddate;
        } else {//如果没有添加有效期则默认为套餐的结束时间
                $insert_arr['vouchertemplate_enddate'] = $quotainfo['voucherquota_endtime'];
        }
        $insert_arr['vouchertemplate_price'] = $price;
        $insert_arr['vouchertemplate_limit'] = $limit;
        $insert_arr['vouchertemplate_store_id'] = $this->store_info['store_id'];
        $insert_arr['vouchertemplate_storename'] = $this->store_info['store_name'];
        $insert_arr['vouchertemplate_sc_id'] = intval(input('post.storeclass_id'));
        $insert_arr['vouchertemplate_creator_id'] = $this->seller_info['member_id'];
        $insert_arr['vouchertemplate_state'] = 1;
        $insert_arr['vouchertemplate_total'] = intval(input('post.txt_template_total')) > 0 ? intval(input('post.txt_template_total')) : 0;
        $insert_arr['vouchertemplate_giveout'] = 0;
        $insert_arr['vouchertemplate_used'] = 0;
        $insert_arr['vouchertemplate_gettype'] = 1;
        $insert_arr['vouchertemplate_adddate'] = TIMESTAMP;
        $insert_arr['vouchertemplate_quotaid'] = isset($quotainfo['voucherquota_id']) ? $quotainfo['voucherquota_id'] : 0;
        $insert_arr['vouchertemplate_points'] = $chooseprice['voucherprice_defaultpoints'];
        $insert_arr['vouchertemplate_eachlimit'] = intval(input('post.eachlimit')) > 0 ? intval(input('post.eachlimit')) : 0;
        $insert_arr['vouchertemplate_if_private'] = intval(input('post.vouchertemplate_if_private'));
		//自定义图片
        if (!empty($_FILES['customimg']['name'])) {
            $file_name = $this->store_info['store_id'] . '_' . date('YmdHis') . rand(10000, 99999) . '.png';
            $res = ds_upload_pic(ATTACH_VOUCHER . DIRECTORY_SEPARATOR . $this->store_info['store_id'], 'customimg', $file_name);
            if ($res['code']) {
                $file_name = $res['data']['file_name'];
                $insert_arr['vouchertemplate_customimg'] = $file_name;
            } else {
                ds_json_encode(10001, $res['msg']);
            }
        }
        $rs = Db::name('vouchertemplate')->insert($insert_arr);
        if ($rs) {
            ds_json_encode(10000, lang('ds_common_op_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }
    }


    /**
     * @api {POST} api/Sellervoucher/get_voucherquota_info 代金券新增/编辑公共数据
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.pricelist  面额列表
     * @apiSuccess {Object[]} result.pricelist.voucherprice  面额
     * @apiSuccess {Object[]} result.pricelist.voucherprice_defaultpoints  兑换积分
     * @apiSuccess {Object[]} result.pricelist.voucherprice_describe  描述
     * @apiSuccess {Object[]} result.pricelist.voucherprice_id  面额ID
     * @apiSuccess {String} result.voucher_buyertimes_limit  买家最多只能拥有同一个店铺尚未消费抵用的店铺代金券最大数量
     */
    public function get_voucherquota_info() {
		$voucher_model = model('voucher');
        //查询面额列表
        $pricelist = Db::name('voucherprice')->order('voucherprice asc')->select()->toArray();
		$quotainfo = $voucher_model->getVoucherquotaCurrent($this->store_info['store_id']);
		$quotainfo['voucherquota_endtime'] = date('Y-m-d',$quotainfo['voucherquota_endtime']);
        if (empty($pricelist)) {
            ds_json_encode(10001, lang('voucher_template_pricelisterror'));
        }
        
        ds_json_encode(10000, '', array('pricelist' => $pricelist,'quotainfo'=>$quotainfo,'voucher_buyertimes_limit' => config('ds_config.voucher_buyertimes_limit')));
    }

    /**
     * @api {POST} api/Sellervoucher/templateadd 代金券模版编辑
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} tid 代金券模版ID
     * @apiParam {String} txt_template_title 代金券模版名称
     * @apiParam {String} txt_template_total 代金券总数
     * @apiParam {String} select_template_price 面额
     * @apiParam {String} txt_template_limit 订单限额
     * @apiParam {String} txt_template_describe 代金券模版描述
     * @apiParam {String} txt_template_enddate 有效期结束时间 YYYY-MM-DD
     * @apiParam {String} storeclass_id 所属机构分类ID
     * @apiParam {String} eachlimit 每人限领张数
     * @apiParam {Int} tstate 代金券模版状态 1:有效 2:失效
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function templateedit() {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        //查询模板信息
        $condition = array();
        $condition[] = array('vouchertemplate_id','=',$t_id);
        $condition[] = array('vouchertemplate_store_id','=',$this->store_info['store_id']);
        $condition[] = array('vouchertemplate_state','=',1);
        $condition[] = array('vouchertemplate_giveout','<=', '0');
        $condition[] = array('vouchertemplate_enddate','>', TIMESTAMP);
        $t_info = Db::name('vouchertemplate')->where($condition)->find();
        if (empty($t_info)) {
            ds_json_encode(10001, lang('param_error'));
        }

        $quotainfo = array();
            //查询套餐信息
            $quotainfo = Db::name('voucherquota')->where(array(
                        'voucherquota_id' => $t_info['vouchertemplate_quotaid'],
                        'voucherquota_storeid' => $this->store_info['store_id']
                    ))->find();
            if (empty($quotainfo)) {
                ds_json_encode(10001, lang('voucher_template_quotanull'));
            }

        $pricelist = Db::name('voucherprice')->order('voucherprice asc')->select()->toArray();
        //验证提交的内容面额不能大于限额
        $data = [
            'txt_template_title' => input('post.txt_template_title'),
            'txt_template_total' => input('post.txt_template_total'),
            'select_template_price' => input('post.select_template_price'),
            'txt_template_limit' => input('post.txt_template_limit'),
            'txt_template_describe' => input('post.txt_template_describe'),
        ];
        $sellervoucher_validate = ds_validate('sellervoucher');
        if (!$sellervoucher_validate->scene('templateedit')->check($data)) {
            ds_json_encode(10001, $sellervoucher_validate->getError());
        }
        //金额验证
        $price = intval(input('post.select_template_price')) > 0 ? intval(input('post.select_template_price')) : 0;
        foreach ($pricelist as $k => $v) {
            if ($v['voucherprice'] == $price) {
                $chooseprice = $v; //取得当前选择的面额记录
            }
        }
        if (empty($chooseprice)) {
            ds_json_encode(10001, lang('voucher_template_pricelisterror'));
        }
        $limit = intval(input('post.txt_template_limit')) > 0 ? intval(input('post.txt_template_limit')) : 0;
        if ($price >= $limit) {
            ds_json_encode(10001, lang('voucher_template_price_error'));
        }
        $update_arr = array();
        $update_arr['vouchertemplate_title'] = trim(input('post.txt_template_title'));
        $update_arr['vouchertemplate_desc'] = trim(input('post.txt_template_describe'));
        if (input('post.txt_template_enddate')) {
            $enddate = strtotime(input('post.txt_template_enddate'));
            if ($enddate > $quotainfo['voucherquota_endtime']) {
                $enddate = $quotainfo['voucherquota_endtime'];
            }
            $update_arr['vouchertemplate_enddate'] = $enddate;
        } else {//如果没有添加有效期则默认为套餐的结束时间
                $update_arr['vouchertemplate_enddate'] = $quotainfo['voucherquota_endtime'];
        }
        $update_arr['vouchertemplate_price'] = $price;
        $update_arr['vouchertemplate_limit'] = $limit;
        $update_arr['vouchertemplate_sc_id'] = intval(input('post.storeclass_id'));
        $update_arr['vouchertemplate_state'] = intval(input('post.tstate')) == 1 ? 1 : 2;
        $update_arr['vouchertemplate_total'] = intval(input('post.txt_template_total')) > 0 ? intval(input('post.txt_template_total')) : 0;
        $update_arr['vouchertemplate_points'] = $chooseprice['voucherprice_defaultpoints'];
        $update_arr['vouchertemplate_eachlimit'] = intval(input('post.eachlimit')) > 0 ? intval(input('post.eachlimit')) : 0;
        $update_arr['vouchertemplate_if_private'] = intval(input('post.vouchertemplate_if_private'));
		//自定义图片
        if (!empty($_FILES['customimg']['name'])) {
            $file_name = $this->store_info['store_id'] . '_' . date('YmdHis') . rand(10000, 99999);
            $res = ds_upload_pic(ATTACH_VOUCHER . DIRECTORY_SEPARATOR . $this->store_info['store_id'], 'customimg', $file_name);
            if ($res['code']) {
                $file_name = $res['data']['file_name'];
                //删除原图
                if (!empty($t_info['vouchertemplate_customimg'])) {//如果模板存在，则删除原模板图片
                    @unlink(BASE_UPLOAD_PATH . DIRECTORY_SEPARATOR . ATTACH_VOUCHER . DIRECTORY_SEPARATOR . $this->store_info['store_id'] . DIRECTORY_SEPARATOR . $t_info['vouchertemplate_customimg']);
                }
                $update_arr['vouchertemplate_customimg'] = $file_name;
            } else {
                ds_json_encode(10001, $res['msg']);
            }
        }

        $rs = Db::name('vouchertemplate')->where(array('vouchertemplate_id' => $t_info['vouchertemplate_id']))->update($update_arr);
        if ($rs) {
            ds_json_encode(10000, lang('ds_common_op_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }
    }

    /**
     * @api {POST} api/Sellervoucher/templatedel 删除代金券
     * @apiVersion 1.0.0
     * @apiGroup Sellervoucher
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} tid 代金券模版ID
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function templatedel() {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        //查询模板信息
        $condition = array();
        $condition[] = array('vouchertemplate_id','=',$t_id);
        $condition[] = array('vouchertemplate_store_id','=',$this->store_info['store_id']);
        $condition[] = array('vouchertemplate_giveout','<=', '0'); //会员没领取过代金券才可删除
        $t_info = Db::name('vouchertemplate')->where($condition)->find();
        if (empty($t_info)) {
            ds_json_encode(10001, lang('param_error'));
        }
        $rs = Db::name('vouchertemplate')->where(array('vouchertemplate_id' => $t_info['vouchertemplate_id']))->delete();
        if ($rs) {
            //删除自定义的图片
            if (trim($t_info['vouchertemplate_customimg'])) {
                @unlink(BASE_UPLOAD_PATH . DIRECTORY_SEPARATOR . ATTACH_VOUCHER . DIRECTORY_SEPARATOR . $this->store_info['store_id'] . DIRECTORY_SEPARATOR . $t_info['vouchertemplate_customimg']);
            }
            ds_json_encode(10000, lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_del_fail'));
        }
    }

    /**
     * 查看代金券详细
     */
    public function templateinfo() {
        $t_id = intval(input('param.tid'));
        if ($t_id <= 0) {
            ds_json_encode(10001, lang('param_error'), 'Sellervoucher/templatelist');
        }
        //查询模板信息
        $param = array();
        $param['vouchertemplate_id'] = $t_id;
        $param['vouchertemplate_store_id'] = $this->store_info['store_id'];
        $t_info = Db::name('vouchertemplate')->where($param)->find();
        ds_json_encode(10000, lang('ds_common_del_succ'), array('t_info' => $t_info));
    }

    /*
     * 把代金券模版设为失效
     */

    private function check_voucher_template_expire($voucher_template_id = '') {
        $condition = array();
        if (empty($voucher_template_id)) {
            $condition[] = array('vouchertemplate_enddate','<', TIMESTAMP);
        } else {
            $condition[] = array('vouchertemplate_id','=',$voucher_template_id);
        }
        $condition[] = array('vouchertemplate_state','=',1);
        Db::name('vouchertemplate')->where($condition)->update(array('vouchertemplate_state' => 2));
    }

}
